import re
import os
import json
import collect
import utils
from openpyxl.utils import get_column_letter

def set_columns_width(sheet, columns_width):
    for index, width in enumerate(columns_width):
        sheet.column_dimensions[get_column_letter(index + 1)].width = width


class ReportGenerator:
    def __init__(self, library, date_to_report):
        """
        :param utils.AccountLibrary library:
        :param date_to_report:
        """
        self.date = date_to_report
        self.library = library
        self.gh_id = None

    def save_excel(self, workbook, name):
        filename = 'output/{} {}.xlsx'.format(self.date, name)
        try:
            workbook.save(filename)
            workbook.close()
        except PermissionError:
            print('无法写入{}，请检查是否在Excel中打开了文件，如有需要请另存为并关闭'.format(filename))

    def date_info(self):
        workbook, sheet = utils.make_workbook()
        set_columns_width(sheet, [ 20, 20, 20, 15])
        sheet.append(['名称', '原始ID',  '图文总阅读次数', '时间'])
        row_index = 1
        print("开始生成表格")
        with open("graphic_reader_info.json", encoding='utf-8', mode='r', errors='ignore') as f:
            for lines in f.readlines():
                try:
                    lines = re.sub('\'', '\"', lines)
                    dic = json.loads(lines)
                    row_index += 1
                    list1 = [dic["nickname"],dic["Id"],dic["all_reading"],dic["date_time"]]
                    sheet.append(list1)
                except:
                    print(lines)
                    pass
        self.save_excel(workbook, '图文总阅读')


if __name__ == '__main__':
    yesterday = utils.get_yesterday()
    date = None
    collect.test_collect()
    ret = ReportGenerator(
        utils.default_library(), date if date else yesterday)
    ret.date_info()
    os.remove('graphic_reader_info.json')